import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { constantRoutes } from './router'

NProgress.configure({ showSpinner: true }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/camera/display'] // no redirect whitelist
const noNeedUser = (r) => {
  return constantRoutes.some(c => c.path === r.path);
}

router.beforeEach(async (to, from, next) => {
  // 启动进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else if (noNeedUser(to)) {
      next()
      NProgress.done()
    } else {
      // 确定用户是否通过getInfo获得了他的权限角色
      const flag = store.getters.flag;
      if (!flag) {
        store.dispatch('user/getInfo')
          .then(async data => {
            try {
              // get user info
              // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
              const { menuList } = data;

              // 根据角色生成可访问路由映射
              const accessRoutes = await store.dispatch('permission/generateRoutes', menuList)

              // dynamically add accessible routes
              router.addRoutes(accessRoutes)

              // hack method to ensure that addRoutes is complete
              // set the replace: true, so the navigation will not leave a history record
              next({ ...to, replace: true })
            } catch (error) {
              // remove token and go to login page to re-login
              console.log(error)
              await store.dispatch('user/resetToken')
              next(`/error?redirect=${to.path}`)
              NProgress.done()
            }
          })
          .catch(e => {
            next('/error?redirect=' + to.fullPath)
            NProgress.done();
          })
      } else {
        next()
        NProgress.done();
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
      NProgress.done();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path === '/error' ? '/' : to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
